﻿using Microsoft.EntityFrameworkCore;
using NewRetail.Application.Components.Goods.Entity;
using System;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace NewRetail.Application.Components.Goods
{
    public interface IAdjustPriceService : IApplicationService
    {
        Task<GoodsAdjustPrice[]> AttachWarehouse(GoodsAdjustPrice[] data);
        Task<GoodsAdjustPrice[]> AttachGoods(GoodsAdjustPrice[] data);
    }

    public class AdjustPriceService : ApplicationService, IAdjustPriceService
    {
        private readonly IRepository<GoodsAdjustPrice> goodsAdjustPrices;
        public AdjustPriceService(IRepository<GoodsAdjustPrice> goodsAdjustPrices)
        {
            this.goodsAdjustPrices = goodsAdjustPrices;
        }

        public async Task<GoodsAdjustPrice[]> AttachWarehouse(GoodsAdjustPrice[] data)
        {
            if (!data.Any())
            {
                return data;
            }

            var ids = data.Select(x => x.warehouseID).ToArray();

            var db = await this.goodsAdjustPrices.GetDbContextAsync();

            var list = await db.Set<Warehouse.Entity.Warehouse>().AsNoTracking()
                .Where(x => ids.Contains(x.Id)).ToArrayAsync();

            foreach (var m in data)
            {
                m.Warehouse = list.FirstOrDefault(x => x.Id == m.warehouseID);
            }

            return data;
        }

        public async Task<GoodsAdjustPrice[]> AttachGoods(GoodsAdjustPrice[] data)
        {
            if (!data.Any())
            {
                return data;
            }

            var ids = data.Select(x => x.goodsID).ToArray();

            var db = await this.goodsAdjustPrices.GetDbContextAsync();

            var list = await db.Set<GoodsInfo>().AsNoTracking()
                .Where(x => ids.Contains(x.Id)).ToArrayAsync();

            foreach (var m in data)
            {
                m.GoodsInfo = list.FirstOrDefault(x => x.Id == m.goodsID);
            }

            return data;
        }
    }
}
